﻿using FastBuild.IISRestart;
using System.Reflection;
using FastBuild.Init.IISRestart;

namespace FastBuild
{
    /// <summary>
    /// 
    /// </summary>
    public static class IISRestartInitExtension
    {
        /// <summary>
        /// 启用IISRestart
        /// </summary>
        /// <param name="option"></param>
        /// <param name="action"></param>
        public static InitOption UseIISRestart(this InitOption option, Action<IISRestartInitOption> action)
        {
            IISRestartInitOption moduleOption = new IISRestartInitOption();
            action?.Invoke(moduleOption);
            if (option != null)
                InitClass.Option = moduleOption;

            return option;
        }
    }
}

namespace FastBuild.Init.IISRestart
{
    internal static class InitClass
    {
        /// <summary>
        /// IISRestart的Option
        /// </summary>
        public static IISRestartInitOption Option { get; set; }

        /// <summary>
        /// 初始化IIS重启
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection InitMethod_ServiceCollection(this IServiceCollection services)
        {
            if (Option == null) return services;

            var callbackType = Assembly.GetEntryAssembly().DefinedTypes.Where(y => y.GetInterface(nameof(IRestart)) is not null).FirstOrDefault();
            if (callbackType is not null)
                services.AddScoped(typeof(IRestart), callbackType);

            return services;
        }

        /// <summary>
        /// 初始化IIS重启
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static WebApplication InitMethod_WebApplication(this WebApplication app)
        {
            if (Option == null) return app;

            var service = app.Services.GetRequiredService(typeof(IISRestartService)) as IISRestartService;

            service.Run(Option);

            //开启重启程序接口
            app.MapGet("/IISRestart", () =>
            {
                //执行拓展方法
                object obj = ServiceContainer.GetService(typeof(IRestart));
                if (obj != null)
                    (obj as IRestart).Execute();
            });

            return app.ConsoleWriteLine($"IISRestart Init Success");
        }
    }
}
